<template>
    <div v-if="userStore.isSuperAdmin">
        <el-text size="large">员工信息</el-text>
        <el-divider style="margin: 10px 0;"></el-divider>
        <el-form :model="queryForm" label-width="120px" style="max-width: 100%; margin: 0 auto;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="账号ID">
                        <el-input-number v-model="queryForm.account_id as number" :min="0" :step="1" step-strictly placeholder="请输入ID" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="昵称">
                        <el-autocomplete v-model="queryForm.account_nickname" :fetch-suggestions="fetchSuggestions('account_nickname')" placeholder="请输入昵称"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="权限">
                        <el-select v-model="queryForm.permission_level as number" placeholder="请选择权限" clearable>
                            <el-option label="超级管理员" :value="0"></el-option>
                            <el-option label="普通管理员" :value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="姓名">
                        <el-autocomplete v-model="queryForm.full_name" :fetch-suggestions="fetchSuggestions('full_name')" placeholder="请输入姓名"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="性别">
                        <el-select v-model="queryForm.gender as boolean" placeholder="请选择性别" clearable>
                            <el-option label="男" :value="true"></el-option>
                            <el-option label="女" :value="false"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="联系方式">
                        <el-autocomplete v-model="queryForm.contact_info" :fetch-suggestions="fetchSuggestions('contact_info')" placeholder="请输入联系方式"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="备注">
                        <el-autocomplete v-model="queryForm.remarks" :fetch-suggestions="fetchSuggestions('remarks')" placeholder="请输入备注"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" @click="searchEmployee" :loading="loading" :icon="Search">查询</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="success" @click="openAddDialog" :icon="Plus">新增</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-divider style="margin: 10px 0;"></el-divider>
        <el-table :data="paginatedEmployeeList" v-if="paginatedEmployeeList.length > 0">
            <el-table-column prop="account_id" label="账号ID" sortable></el-table-column>
            <el-table-column prop="account_nickname" label="昵称" sortable></el-table-column>
            <el-table-column prop="account_password" label="密码" sortable>
                <template #default="scope">
                    <el-input v-model="scope.row.account_password" type="password" show-password readonly></el-input>
                </template>
            </el-table-column>
            <el-table-column prop="permission_level" label="权限" sortable>
                <template #default="scope">
                    <el-tag>{{ scope.row.permission_level === 0 ? '超级管理员' : '普通管理员' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="full_name" label="姓名" sortable></el-table-column>
            <el-table-column prop="gender" label="性别" sortable>
                <template #default="scope">
                    <el-tag>{{ scope.row.gender ? '男' : '女' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="contact_info" label="联系方式" sortable></el-table-column>
            <el-table-column prop="remarks" label="备注" sortable></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-container style="width: 4.5rem;">
                        <el-button type="primary" :icon="Edit" circle @click="openEditDialog(scope.row)"></el-button>
                        <el-button type="danger" :icon="Delete" circle @click="openDeleteDialog(scope.row)"></el-button>
                    </el-container>
                </template>
            </el-table-column>
        </el-table>
        <el-empty v-else description="没找到数据呢，亲~"></el-empty>
        <el-pagination
            v-if="total > 0"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
        <AddDialog ref="addEmployeeDialog" @refresh="searchEmployee" />
        <EditDialog ref="editEmployeeDialog" @refresh="searchEmployee" />
        <DeleteDialog ref="deleteEmployeeDialog" @refresh="searchEmployee" />
    </div>
    <div v-else>
        <el-empty description="您没有权限访问此页面"></el-empty>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import AddDialog from '@/components/AddDialog.vue';
import EditDialog from '@/components/EditDialog.vue';
import DeleteDialog from '@/components/DeleteDialog.vue';
import type { EmployeeQueryForm, Employee, FormItem } from '@/types/interface';
import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

const queryForm = reactive<EmployeeQueryForm>({
    account_id: null as any,
    account_nickname: '',
    account_password: '',
    permission_level: null,
    full_name: '',
    gender: null,
    contact_info: '',
    remarks: ''
});

const employeeList = ref<Employee[]>([
    { account_id: 1, account_nickname: '用户A', account_password: '密码A', permission_level: 0, full_name: '姓名A', gender: true, contact_info: '联系方式A', remarks: '备注A' },
    { account_id: 2, account_nickname: '用户B', account_password: '密码B', permission_level: 1, full_name: '姓名B', gender: false, contact_info: '联系方式B', remarks: '备注B' },
    { account_id: 3, account_nickname: '用户C', account_password: '密码C', permission_level: 1, full_name: '姓名C', gender: true, contact_info: '联系方式C', remarks: '备注C' }
]);
const total = ref(employeeList.value.length);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

const paginatedEmployeeList = computed(() => {
    if (!employeeList.value || employeeList.value.length === 0) {
        return [];
    }
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return employeeList.value.slice(start, end);
});

// 获取建议
function fetchSuggestions(field: keyof EmployeeQueryForm): (queryString: string, cb: (suggestions: { value: string }[]) => void) => void {
    return async (queryString: string, cb: (suggestions: { value: string }[]) => void) => {
        if (!queryString) {
            cb([]);
            return;
        }
        try {
            const response = await axios.get(`/api/employee/suggestions`, {
                params: { field, query: queryString }
            });
            cb(response.data.map((item: string) => ({ value: item })));
        } catch (error) {
            console.error(`获取${field}建议失败:`, error);
            cb([]);
        }
    };
}

// 查询员工信息
async function searchEmployee() {
    try {
        loading.value = true;
        const response = await axios.get('/api/employee', {
            params: {
                ...queryForm,
                page: 1,
                pageSize: 1000 // 假设最大查询1000条数据
            }
        });
        employeeList.value = response.data.items;
        total.value = response.data.total;
        currentPage.value = 1;
        ElMessage({
            message: '查询员工信息成功',
            type: 'success',
        });
    } catch (error) {
        console.error('查询员工信息失败:', error);
        ElMessage({
            message: '查询员工信息失败',
            type: 'error',
        });
    } finally {
        loading.value = false;
    }
}

// 分页处理
function handlePageChange(page: number) {
    currentPage.value = page;
}

function handleSizeChange(size: number) {
    pageSize.value = size;
    currentPage.value = 1;
}

const addEmployeeDialog = ref();
const editEmployeeDialog = ref();
const deleteEmployeeDialog = ref();

// 打开新增对话框
function openAddDialog() {
    addEmployeeDialog.value.openDialog({
        title: '新建员工信息记录',
        formItems: [
            { label: '账号昵称', prop: 'account_nickname', value: '', rules: [
                { required: true, message: '账号ID不能为空', trigger: 'blur' },
                { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '密码', prop: 'account_password', value: '', rules: [
                { required: true, message: '密码不能为空', trigger: 'blur' },
                { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
            ] },
            { label: '权限', prop: 'permission_level', value: null, rules: [
                { required: true, message: '权限不能为空', trigger: 'blur' }
            ] },
            { label: '姓名', prop: 'full_name', value: '', rules: [
                { required: true, message: '姓名不能为空', trigger: 'blur' },
                { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '性别', prop: 'gender', value: null, rules: [
                { required: true, message: '性别不能为空', trigger: 'blur' }
            ] },
            { label: '联系方式', prop: 'contact_info', value: '', rules: [
                { required: true, message: '联系方式不能为空', trigger: 'blur' },
                { max: 50, message: '联系方式长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: '', rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            addEmployeeDialog.value.visible = false;
            ElMessage({
                message: '已取消新建',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await addEmployeeDialog.value.formRef.validate();
                await axios.post('/api/employee', addEmployeeDialog.value.formData);
                ElMessage({
                    message: '新建员工信息记录成功',
                    type: 'success',
                });
                addEmployeeDialog.value.visible = false;
                searchEmployee();
            } catch (error) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败',
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 打开编辑对话框
function openEditDialog(row: Employee) {
    editEmployeeDialog.value.openDialog({
        title: '编辑员工信息记录',
        formItems: [
            { label: '昵称', prop: 'account_nickname', value: row.account_nickname, rules: [
                { required: true, message: '昵称不能为空', trigger: 'blur' },
                { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '密码', prop: 'account_password', value: row.account_password, rules: [
                { required: true, message: '密码不能为空', trigger: 'blur' },
                { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
            ] },
            { label: '权限', prop: 'permission_level', value: row.permission_level, rules: [
                { required: true, message: '权限不能为空', trigger: 'blur' }
            ] },
            { label: '姓名', prop: 'full_name', value: row.full_name, rules: [
                { required: true, message: '姓名不能为空', trigger: 'blur' },
                { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '性别', prop: 'gender', value: row.gender, rules: [
                { required: true, message: '性别不能为空', trigger: 'blur' }
            ] },
            { label: '联系方式', prop: 'contact_info', value: row.contact_info, rules: [
                { required: true, message: '联系方式不能为空', trigger: 'blur' },
                { max: 50, message: '联系方式长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: row.remarks, rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            editEmployeeDialog.value.visible = false;
            ElMessage({
                message: '已取消编辑',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await editEmployeeDialog.value.formRef.validate();
                await axios.put(`/api/employee/${row.account_id}`, editEmployeeDialog.value.formData);
                ElMessage({
                    message: '编辑员工信息记录成功',
                    type: 'success',
                });
                editEmployeeDialog.value.visible = false;
                searchEmployee();
            } catch (error) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败',
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 打开删除对话框
function openDeleteDialog(row: Employee) {
    deleteEmployeeDialog.value.openDialog({
        title: '删除员工信息记录',
        content: `是否删除账号ID为 ${row.account_id} 的记录？`,
        handleCancel: () => {
            deleteEmployeeDialog.value.visible = false;
            ElMessage({
                message: '已取消删除',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await axios.delete(`/api/employee/${row.account_id}`);
                ElMessage({
                    message: '删除员工信息记录成功',
                    type: 'success',
                });
                deleteEmployeeDialog.value.visible = false;
                searchEmployee();
            } catch (error) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败',
                    type: 'error',
                });
            }
        }
    });
}

onMounted(() => {
    searchEmployee();
});
</script>

<style scoped>
.el-form-item {
    margin: 10px 0;
}
.el-input,
.el-button {
    width: 100%;
}
.el-form {
    padding: 20px;
}
.el-form-item .el-form-item__label {
    padding-right: 20px;
}
</style>